﻿using System;
using System.Collections.Generic;
using System.Linq;
using com.kmer.Cache;
using com.kmer.models;
using com.kmer.interfaces;
using com.kmer.enums;

namespace com.kmer.db
{
    public class MemberShipFactory : IUserFactory
    {
        static bool IsExist(int cusId, km_platformEntities dc = null)
        {
            dc = dc ?? (dc = new km_platformEntities());
            return dc.sys_users.Any(u => u.UserID == cusId);
        }
        static User getUser(sys_users user)
        {
            var newUser = new User()
            {
                CusId = user.UserID,
                CreateDate = user.CreateDate ?? DateTime.Now,
                ID = Guid.NewGuid(),
                LoginId = user.LoginAccount,
                NickName = user.UserName,
                RealName = user.UserName,
                Tel = user.Tel,
                City = user.City,
                Province = user.Province
            };
            return newUser;
        }
        public User GetUserByUserID(int cusId)
        {
            User newUser = null;
            if (cusId > 0)
            {
                using (var dc = new km_platformEntities())
                {
                    newUser = getUser(dc.sys_users.FirstOrDefault(i => i.UserID == cusId));
                }
            }
            return newUser;
        }

        public User Login(string loginName, string pass)
        {
            var dc = new km_platformEntities();
            var reg = dc.sys_users.FirstOrDefault(
                    u => u.PassWord == pass
                        && (u.LoginAccount == loginName || u.Tel == loginName || u.Email == loginName));
            if (reg == null)
            {
                throw new Exception("您输入的用户名或密码错误,请重新输入！");
            }
            if (reg.IsEffective == false)
            {
                throw new Exception("您的账号已经被禁用，请与服务人员联系！");
            }
            if (!dc.t_order_userweight.Any(t => t.UserID == reg.UserID))
                throw new Exception("您的账号没有访问订货会系统权限，请与服务人员联系！");
            var user = getUser(reg);
            //更新个人信息(登陆次数，上次登陆时间，最后登陆时间)
            //reg.PrvLoginDate = reg.LastLoginDate;
            //reg.LastLoginDate = DateTime.Now;
            //reg.LoginCount++;
            //reg.IP = HttpContext.Current.Request.GetClientIpAddress();
            //dc.SaveChanges();
            //TODO:HookService.Instance.Invoke((int)HookTypes.AFTER_USER_LOGIN, UserInfo.CusID, loginCount, lastLoginDate);
            //OnlineUsers.AddAndRefresh(reg.UserID,reg.UserName);
            return user;
        }

        public string GetRefreshToken(User loginUser)
        {
            var guid = Guid.NewGuid();
            RedisCache.AddInt($"rt:{guid}", loginUser.CusId, 60 * 24 * 30);
            return guid.ToString();
        }

        /// <summary>
        /// 根据刷新Token获取用户ID
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public int GetUserIdFromRefres(string key)
        {
            if (!RedisCache.Exists($"rt:{key}"))
            {
                Log.Error($"刷新Token已经过期{key}", "RefreshToken");
                return 0;
            }
            return RedisCache.GetInt($"rt:{key}", 0);
        }

        public User Create(string loginName, string nickName, string pass, string tel, string email, UserComeFrom comeFrom, int invId = 0)
        {
            throw new NotImplementedException();
        }

        public void LoginOut()
        {
            throw new NotImplementedException();
        }

        public int GetUserIdByOpenId(string openId, int ThirdPart)
        {
            throw new NotImplementedException();
        }

        public bool CanIFreeBuy(int cusId)
        {
            throw new NotImplementedException();
        }

        public bool AmIVip(int cusId)
        {
            throw new NotImplementedException();
        }

        public IList<int> GetMyRankList(int cusId)
        {
            throw new NotImplementedException();
        }

        public string GetOpenIdByUserId(int userId, int ThirdPart)
        {
            throw new NotImplementedException();
        }

        public string GetUserName(int cusId, string prefix = "")
        {
            throw new NotImplementedException();
        }

        public void DoLogin(User user)
        {
            throw new NotImplementedException();
        }
    }
}
